package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/design-linked-list/description/
 * @create 2025/9/28 17:25
 * @since JDK17
 */

public class MyLinkedList {
    ListNode head;
    public MyLinkedList() {
        head = new ListNode(-1, null);
    }

    public int get(int index) {
        var p = head;
        for (int i = 0; i <= index && p != null; i++) {
            p = p.next;
        }
        return p == null ? -1 : p.val;
    }

    public void addAtHead(int val) {
        var temp = head.next;
        head.next = new ListNode(val, temp);
    }

    public void addAtTail(int val) {
        var p = head;
        for (; p.next != null; p = p.next);
        p.next = new ListNode(val);
    }

    public void addAtIndex(int index, int val) {
        var p = head;
        for (int i = 0; i < index && p != null; i++) {
            p = p.next;
        }
        if (p == null) {
            return ;
        }
        var temp = p.next;
        p.next = new ListNode(val, temp);
    }

    public void deleteAtIndex(int index) {
        var p = head;
        for (int i = 0; i < index && p != null; i++) {
            p = p.next;
        }
        if (p == null || p.next == null) {
            return;
        }
        p.next = p.next.next;
    }
}
